package com.fy.service.component.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fy.framework.common.utils.AesEncodeUtil;
import com.fy.framework.common.utils.JwtToken;

import io.jsonwebtoken.Claims;

/**
 * 从 {@code HttpServletRequest} 获取一些信息
 * 
 * @author zhshuo
 * @date 2021/12/8 18:15
 */
@SuppressWarnings("all")
public final class RequestUtil {

    /**
     * 获取当前请求中的用户ID
     * 
     * @return
     */
    public static Long getUserId() {
        ServletRequestAttributes servletRequestAttributes =
            (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = getToken(request);
        if (token == null) {
            return -1L;
        } else {
            Long paramsFromToken = null;

            try {
                paramsFromToken = (Long)getParamsFromToken(token, "userId", Long.class);
            } catch (Exception var5) {
                String paramsFromToken2 = (String)getParamsFromToken(token, "userId", String.class);
                if (StringUtils.isNotBlank(paramsFromToken2)) {
                    paramsFromToken = Long.parseLong(paramsFromToken2);
                }
            }

            return paramsFromToken;
        }
    }

    private static <T> T getParamsFromToken(String token, String claimKey, Class<T> clazz) {
        Claims claims = JwtToken.getClaimFromToken(token);
        return claims.get(claimKey, clazz);
    }

    private static String getToken(HttpServletRequest httpServletRequest) {
        String authorization = httpServletRequest.getHeader("token");
        if (StringUtils.isBlank(authorization)) {
            authorization = httpServletRequest.getHeader("Authorization");
            if (StringUtils.isNotBlank(authorization)) {
                authorization = AesEncodeUtil.decrypt(authorization);
            }
        }

        return authorization;
    }

}
